'''
Created on 2011-5-1

@author: edison
'''
import sys
import urllib
import urllib2
import time
import hashlib
 
class TaoBaoAPI(object):
    def __init__(self):
        self.localTime = time.localtime()
        self.sercetCode = 'c9c558de316a84e6f09199e227a942a7'
        self.appKey = '12250564'
        self.taobaoUrl = 'http://gw.api.taobao.com/router/rest'
        
        self.param = {
                'app_key':self.appKey,
                'format':'json',
                'v':'2.0',
                'method':'',
                'timestamp':time.strftime('%Y-%m-%d %X', self.localTime)
        }
        
    def setParam (self, field,value):
        self.param[field] = value
        
    def getParam(self,field):
        try:
            value = self.param[field].encode('utf8')
        except KeyError:
            value = None
        return value
    
    def setFormat(self, format):
        if format in ('json','xml'): self.setParam('format', format)
        
    def setMethod(self, method):
        self.setParam('method', method)
        
    def sign(self):
        src = self.sercetCode + ''.join("%s%s" % (k,v.encode('utf8')) for k, v in sorted(self.param.items()))
        self.setParam('sign', hashlib.md5(src).hexdigest().upper())
    
        
    def request(self):
        formData = urllib.urlencode(self.param)
        try:
            urlopen = urllib2.urlopen(self.taobaoUrl, formData)
#        print formData
            rsp = urlopen.read()
            rsp = rsp.decode('UTF-8')
        except urllib2.URLError,e:
            print >>sys.stderr, "%s" % e
            rsp = None
        return rsp
    
#class TaoBaoItem(TaoBaoAPI):
#    
#    def setNumiid(self,num):
#        self.setParam('num_iid', num)
#    
#    def getItem(self,num):
#        self.setMethod('taobao.item.get')
#        self.setParam('fields', 'detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtual')
#        self.setNumiid(num)
#        self.sign()
#        return self.request()
    
#if __name__ == '__main__':
#    taobao = TaoBaoItem()
#    print taobao.getItem(num = '8224836714')        